﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack )
            {
                FillData();
            }
        }
        //填充数据
        private void FillData()
        {
            var sql = "select * from Articles";
            var dt = DbHelep .GetData(sql);
            Giv .DataSource = dt;
            Giv .DataBind();
        }
        //取消编辑
        protected void Giv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Giv.EditIndex = -1;
            FillData();
        }
        //删除
        protected void Giv_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var Id = GetCell(e.RowIndex, 0);
            var sql = string.Format("delete from Articles where id={0}", Id);
            DbHelep.CRUD(sql);
            Giv .EditIndex = -1;
            FillData();

        }

        private object GetCell(int rowIndex, int columnIndex)
        {
          
            var cell = Giv .Rows[rowIndex].Cells[columnIndex];
            /* var res = cell.Controls.Count > 0 ? ((TextBox)cell.Controls[0]).Text : cell.Text;
             return res;*/
            var  res = string.Empty;
            if (cell.Controls.Count > 0)
            {
                var t = cell.Controls[0];
                var txtBox = (TextBox)t;
                res  = txtBox.Text;
            }
            else
            {
                res  = cell.Text;
            }

            return res;
        }

        //编辑
        protected void Giv_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Giv.EditIndex = e.NewEditIndex;
            FillData();

        }
        //更改
        protected void Giv_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var   idstring = GetCell(e.RowIndex, 0);
            var isok = int.TryParse(idstring, out int id);
            var Id = GetCell(e.RowIndex, 0);
            var Title = GetCell(e.RowIndex, 1);
            var Content = GetCell(e.RowIndex, 2);
            var Author = GetCell(e.RowIndex, 3);
            var Remarks = GetCell(e.RowIndex, 4);
            if (isok)
            {
                //更改sql语句
                var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}' where id='{4}'", Title, Content, Author, Remarks, Id);
                DbHelep .CRUD (sql);
            }
            else
            {
                //添加
                var sql = string.Format("insert into Articles (Title,Content,Author,Remark)values('{0}', '{1}', '{2}', '{3}') ", Title, Content, Author, Remarks);
                DbHelep .CRUD (sql);
            }
            Giv.EditIndex = -1;
            FillData();
        }
    }
}